import {Reducer} from 'redux';
import {history} from 'umi';
import {Effect} from 'dva';
import {message} from 'antd';
import {stringify} from 'querystring';

import {accountLogin} from '@/services/login';
import {setAuthority} from '@/utils/authority';
import {getPageQuery} from '@/utils/utils';

export interface StateType {
  status?: 'ok' | 'error';
  desc?: string;
  type?: string;
  token?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    * login({payload}, {call, put}) {
      const response = yield call(accountLogin, payload);
      if (response.code) {
        response.status = statusOE(response.code.key);
        response.desc = response.code.desc;
        if (response.code.key === 'code_sys_ok') {
          if (response.attach.role === 1) {
            response.currentAuthority = "admin";
            response.attach.userTypes = [1,3,4];
          }
          if (response.attach.role === 0) {
            response.currentAuthority = "user";
          }
        } else {
          response.currentAuthority = "guest";
        }
      }
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.status === 'ok') {
        localStorage.setItem('token', response.attach.token);
        localStorage.setItem('userName', payload.userName);
        localStorage.setItem('userTypes', JSON.stringify(response.attach.userTypes));

        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        message.success(localStorage.getItem("userName") + ' 登录成功！');
        let {redirect} = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (window.routerBase !== '/') {
              redirect = redirect.replace(window.routerBase, '/');
            }
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
          for (let i = 0; i < redirect.length; i++) {
            if (redirect.substr(0, 1) === "/") {
              redirect = redirect.substr(1);
            } else {
              redirect = "/" + redirect;
              break;
            }
          }
        }
        history.replace(redirect || '/');
      }
    },

    logout() {
      const {redirect} = getPageQuery();
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        localStorage.setItem('token', "");
        localStorage.setItem('userName', "");
        localStorage.setItem('userTypes', "");
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, {payload}) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        desc: payload.desc,
      };
    },
  },
};

const statusOE = (a: string | number | undefined) => {
  if (a && a.toString().indexOf("ok") === -1) {
    return 'error';
  } else {
    return 'ok'
  }
}

export default Model;
